/**
 * bean对象操作
 *
 * @author zhaowq 2015
 */
package utils;

import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.DataBinder;

public class BeanUtil {

    private static class SYPropertyEditor {
        private Class<?> clazz;
        private String name;
        private PropertyEditor pe;

        private SYPropertyEditor(Class<?> clazz, String name, PropertyEditor pe) {
            super();
            this.clazz = clazz;
            this.name = name;
            this.pe = pe;
        }

        private SYPropertyEditor() {
            super();
        }

        public Class<?> getClazz() {
            return clazz;
        }

        public void setClazz(Class<?> clazz) {
            this.clazz = clazz;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public PropertyEditor getPe() {
            return pe;
        }

        public void setPe(PropertyEditor pe) {
            this.pe = pe;
        }
    }

    /**
     * 获取属性编辑对象
     *
     * @param clazz 属性对应的类
     * @param name 属性名
     * @param pe 该属性编辑器
     * @return {@link SYPropertyEditor}
     */
    public static SYPropertyEditor getSYPropertyEditor(Class<?> clazz, String name, PropertyEditor pe) {
        return new SYPropertyEditor(clazz, name, pe);
    }

    /**
     * 将Map对象转化为指定对象
     *
     * @param <T> 泛型
     * @param clazz 要转化成的类
     * @param map 数据源Map
     * @param editors 属性编辑对象
     * @return 转化成的bean对象
     */
    public static <T> T map2bean(Class<T> clazz, Map<String, Object> map, SYPropertyEditor... editors) {
        T target = BeanUtils.instantiateClass(clazz);
        DataBinder db = new DataBinder(target);
        if (editors != null) {
            for (SYPropertyEditor sy : editors) {
                db.registerCustomEditor(sy.getClazz(), sy.getName(), sy.getPe());
            }
        }
        MutablePropertyValues mv = new MutablePropertyValues(map);
        db.bind(mv);
        return target;
    }

    /**
     * 将bean转化为map对象
     *
     * @param bean 数据源类
     * @param ignore 要忽略的字段
     * @return 转化成的map对象
     */
    public static Map<String, Object> bean2map(Object bean, String... ignore) {
        List<String> list = ignore == null ? new ArrayList<>() : Arrays.asList(ignore);
        Map<String, Object> map = new HashMap<>();
        BeanWrapperImpl bi = new BeanWrapperImpl(bean);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            String name = pd.getName();
            if (list.indexOf(name) != -1 || "class".equals(name)) {
                continue;
            }
            Object value = bi.getPropertyValue(name);
            map.put(name, value);
        }
        return map;
    }

    /**
     * 将bean数组转化为map数组对象
     *
     * @param beans 数据源bean数组
     * @param ignore 要忽略的字段
     * @return map数组对象
     */
    public static List<Map<String, Object>> listBean2listMap(List<?> beans, String... ignore) {
        List<Map<String, Object>> ret = new ArrayList<>();
        for (Object bean : beans) {
            ret.add(bean2map(bean, ignore));
        }
        return ret;
    }

    /**
     * 获取字段的值
     *
     * @param field 字段
     * @param target 对象
     * @return 字段的值
     */
    public static Object getField(Field field, Object target) {
        ReflectionUtils.makeAccessible(field);
        return ReflectionUtils.getField(field, target);
    }

    /**
     * 获取字段你的值
     *
     * @param fieldName 字段名称
     * @param target 对象
     * @return 字段的值
     */
    public static Object getField(String fieldName, Object target) {
        Field field = findField(target.getClass(), fieldName);
        if (field != null) {
            return getField(field, target);
        } else {
            return null;
        }
    }

    /**
     * 根据字段名获取字段
     *
     * @param clazz class
     * @param fieldName 字段名
     * @return {@link Field}
     */
    public static Field findField(Class<?> clazz, String fieldName) {
        return ReflectionUtils.findField(clazz, fieldName);
    }

    /**
     * 设置字段的值
     *
     * @param field 字段
     * @param target 对象
     * @param value 值
     */
    public static void setField(Field field, Object target, Object value) {
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, target, value);
    }

    public static void setField(String fieldName, Object target, Object value) {
        Field field = findField(target.getClass(), fieldName);
        if (null != field) {
            setField(field, target, value);
        }
    }

    public static void setStaticField(String fieldName, Class<?> clazz, Object value) {
        Field field = findField(clazz, fieldName);
        if (null != field) {
            setField(field, clazz, value);
        }
    }

    /**
     * 获取由指定annotation标注的域(字段)
     *
     * @param <A> 泛型
     * @param clazz 类对象
     * @param annotationType annotation类型
     * @return
     */
    public static <A extends Annotation> List<Field> getFieldsByAnnotaion(Class<?> clazz,
        final Class<A> annotationType) {
        final List<Field> list = new ArrayList<>();
        ReflectionUtils.doWithFields(clazz, list::add, field -> null != field.getAnnotation(annotationType));
        return list;
    }

    /**
     * 获取由指定annotation标注的方法
     *
     * @param <A> 泛型
     * @param clazz 类对象
     * @param annotationType annotation类型
     * @return 方法
     */
    public static <A extends Annotation> List<Method> getMethodsByAnnotation(Class<?> clazz,
        final Class<A> annotationType) {
        final List<Method> list = new ArrayList<>();
        ReflectionUtils.doWithMethods(clazz, list::add,
            method -> null != AnnotationUtils.findAnnotation(method, annotationType));
        return list;
    }

    /**
     * bo 转换成 xml
     *
     * @param bean
     * @param out
     * @param config 配置<br/>
     * jaxb.encoding					string<br/>
     * jaxb.formatted.output			boolean<br/>
     * jaxb.schemaLocation				string<br/>
     * jaxb.noNamespaceSchemaLocation	string<br/>
     * jaxb.fragment 					boolean<br/>
     * @throws JAXBException
     */
    public static void bean2xml(Object bean, OutputStream out, Map<String, Object> config) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(bean.getClass());
        Marshaller mar = context.createMarshaller();
        if (null != config) {
            for (Entry<String, Object> entity : config.entrySet()) {
                mar.setProperty(entity.getKey(), entity.getValue());
            }
        }
        mar.marshal(bean, out);
    }

    /**
     * bo 转换成 xml
     *
     * @param bean
     * @param config 配置<br/>
     * jaxb.encoding					string<br/>
     * jaxb.formatted.output			boolean<br/>
     * jaxb.schemaLocation				string<br/>
     * jaxb.noNamespaceSchemaLocation	string<br/>
     * jaxb.fragment 					boolean<br/>
     * @throws JAXBException
     */
    public static void bean2xml(Object bean, Writer w, Map<String, Object> config) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(bean.getClass());
        Marshaller mar = context.createMarshaller();
        if (null != config) {
            for (Entry<String, Object> entity : config.entrySet()) {
                mar.setProperty(entity.getKey(), entity.getValue());
            }
        }
        mar.marshal(bean, w);
    }

    /**
     * xml to bo
     *
     * @param <T>
     * @param clazz
     * @param in
     * @return
     * @throws JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2bean(Class<T> clazz, InputStream in) throws JAXBException {
//        JAXBContext context = JAXBContext.newInstance(clazz);
//        Unmarshaller umar = context.createUnmarshaller();
//        return (T) umar.unmarshal(in);
        return null;
    }

    /**
     * xml to bo
     *
     * @param <T>
     * @param clazz
     * @param reader
     * @return
     * @throws JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2bean(Class<T> clazz, Reader reader) throws JAXBException {
//        JAXBContext context = JAXBContext.newInstance(clazz);
//        Unmarshaller umar = context.createUnmarshaller();
//        return (T) umar.unmarshal(reader);
        return null;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void copyCollection(Collection source, Collection target, boolean append) {
        Assert.notNull(source);
        Assert.notNull(target);
        if (!append) {
            target.clear();
        }
        target.addAll(source);
    }

    /**
     * 对象属性拷贝
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        copyProperties(source, target, null, null);
    }

    @SuppressWarnings("rawtypes")
    public static void copyProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties)
    throws BeansException {

        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");

        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException(
                    "Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable
                        .getName() + "]");
            }
            actualEditable = editable;
        }
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(
                targetPd.getName())))) {
                PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }

                        if (value instanceof Collection) {
                            Method targetReadMethod = targetPd.getReadMethod();
                            Object targetValue = targetReadMethod.invoke(target);
                            if (null != targetValue) {
                                copyCollection((Collection) value, (Collection) targetValue, false);
                                continue;
                            }
                        }

                        writeMethod.invoke(target, value);
                    } catch (Exception ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }

}
